package com.thd.springboottest.sso.client.filter;

import com.thd.springboottest.sso.client.service.SessionIdUtil;
import com.thd.springboottest.sso.client.vo.Store;
import com.thd.springboottest.sso.vo.AuthBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * com.thd.springboottest.sso.client.filter.AuthFilter
 *
 * @author: wanglei62
 * @DATE: 2021/8/22 14:44
 **/
public class AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String sessionId = SessionIdUtil.getSessionId(request);
        System.out.println(" 过滤器执行  ...... ");
        if(null == sessionId || sessionId.length() == 0){
            response.getWriter().write("unlogin (sessionId not be found), please login first ...");
            return ;
        }
        AuthBean auth = Store.findBySessionId(sessionId);
        if(null == auth){
            response.getWriter().write("unlogin (sessionId be found but auth info not be found), please login first ...");
            return ;
        }
        AuthBean authChecked = SessionIdUtil.checkSsoToken(auth.getSsoToken());
        if(null != authChecked){
            filterChain.doFilter(request,response);
        }else{
            response.getWriter().write("unlogin (sessionId be found and auth info  be found , but sso check failure), please login first ...");
            return ;
        }

    }
}
